package cn.lsh.comparator;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.StringTokenizer;

public class LineSortComparator extends WritableComparator {
	private final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");

	public LineSortComparator() {
		super(Text.class, true);
	}

	@Override
	public int compare(WritableComparable a, WritableComparable b) {
		if (false) {
			StringTokenizer stA = new StringTokenizer(a.toString());
			StringTokenizer stB = new StringTokenizer(b.toString());
			LocalDate dateA = LocalDate.parse(stA.nextToken(), dtf);
			LocalDate dateB = LocalDate.parse(stB.nextToken(), dtf);
			stA.nextToken();
			String wdsA = stA.nextToken();
			int wdA = Integer.parseInt(wdsA.substring(0, wdsA.length() - 1));
			stB.nextToken();
			String wdsB = stB.nextToken();
			int wdB = Integer.parseInt(wdsB.substring(0, wdsB.length() - 1));
			int i = dateA.compareTo(dateB);
			if (i == 0) {
				return Integer.compare(wdA, wdB);
			}
			return i;
		} else {
			return Integer.valueOf(a.toString()).compareTo(Integer.valueOf(b.toString()));
		}
	}

}
